/*
 * @Author: 李泽琛
 * @Date: 2021-06-08 11:36:06
 * @LastEditTime: 2021-08-31 11:39:36
 * @Description:
 */

const { query } = require("../mysql");
// const { query } = require("../access");

function handelPoint(point) {
  let p_str = "";
  const reg = /[\u4e00-\u9fa5]/g;
  if (reg.test(point)) {
    p_str = point.replace(/[a-z,A-Z]{2,5}/, (a, b) => {
      return "#" + a;
    });
  } else {
    p_str = point + "#BGD";
  }
  return p_str;
}

function pointToLine(AirwayName, startPoint, endPoint) {
  return `${AirwayName}#${handelPoint(startPoint)}#${handelPoint(endPoint)};`;
}

async function handelPointByAirLine(item) {
  const { StartAirportID, StartAirportName, EndAirportID, EndAirportName, FLIGHT_AIRLINE_ID } = item;

  console.log(`正在处理 ${StartAirportName} => ${EndAirportName} 数据...`);

  const res = await query(`select AirwayName,StartPointName,EndPointName from flight_airline_point where FLIGHT_AIRLINE_ID = '${FLIGHT_AIRLINE_ID}'`);

  const points = [res[0]];
  for (let i = 1; i < res.length; i++) {
    const lastPoint = points[points.length - 1];
    const thisPoint = res[i];

    if (lastPoint.AirwayName == thisPoint.AirwayName) {
      lastPoint.EndPointName = thisPoint.EndPointName;
    } else {
      points.push(thisPoint);
    }
  }

  let airline_str = StartAirportID + ";";
  try {
    for (let item of points) {
      airline_str += pointToLine(item.AirwayName, item.StartPointName, item.EndPointName);
    }
  } catch (error) {
    airline_str += "";
    console.log(points + "chucuo");
  }

  airline_str += EndAirportID;
  console.log(` ${StartAirportName} => ${EndAirportName} 数据处理完成`);
  airline_str1 = airline_str.slice(0, 250);
  airline_str2 = airline_str.slice(250, 500);
  return {
    FLIGHT_AIRLINE_ID,
    StartAirportName,
    EndAirportName,
    airline_str,
    airline_str1,
    airline_str2,
  };
}

async function handleByPage(pageSize, pageNum) {
  const airlineList = await query(`select * from flight_airline where LineType = '国内班机航线'  limit ${pageSize} offset ${(pageNum - 1) * pageSize}`);
  const result = [];
  for (let item of airlineList) {
    const obj = await handelPointByAirLine(item);
    result.push(obj);
  }
  return result;
}
module.exports = { handleByPage, handelPointByAirLine };
